package com.engine.common.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class SimpleReadAndWriteFileUtil {

    public static String ReadFile(String path)
    {
        try {
            String fileName =path;
            BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName)); //相对文件路径，如果是放在项目文件夹下，则为new FileReader("test.txt");
            String x;
            String str="";
            while ((x=bufferedReader.readLine()) != null){
                str+=x;
                str+="\n";
            }
            return str;
        }
        catch (IOException e)
        {
            log.error(e.getMessage(),e);
            return "";
        }
    }
    //读取Resource下的文件
    public static String ReadFileInResource(String path)
    {
        try {
            String fileName =path;
            BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(SimpleReadAndWriteFileUtil.class.getResourceAsStream(fileName)));
            String x;
            String str="";
            while ((x=bufferedReader.readLine()) != null){
                str+=x;
                str+="\n";
            }
            return str;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return "";
        }
    }

    public static void WriteFile(String content, String fileName) {
        FileWriter fwriter=null;
        try {
            // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
            fwriter = new FileWriter(fileName);
            fwriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fwriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
